package com.cynteka.cyfoman.ui.collection.factory;

import com.cynteka.cyfoman.ui.collection.CollectionTreeModel;
import org.apache.commons.chain.Command;
import org.apache.commons.chain.impl.ContextBase;
import org.jdesktop.swingx.JXTreeTable;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * User: Sergey
 * Date: 09.08.11
 * Time: 23:30
 */
public class TreeTableCollectionWidgetFactory extends AbstractCollectionWidgetFactory {


    protected JXTreeTable createTable() {
        final JXTreeTable treeTable = new JXTreeTable();

        final TreeSelectionListener listener = new TreeSelectionListener() {
            @Override
            public void valueChanged(TreeSelectionEvent e) {
                initCatalog();
                if(getCatalog() != null) {
                    Command cmd = getCatalog().getCommand(SELECTION_CHANGED_CMD);
                    if(cmd != null) {
                        TreePath[] paths = e.getPaths();
                        if(paths.length > 0) {
                            TreePath path = paths[0];
                            Object lastPathComponent = path.getLastPathComponent();
                            if(lastPathComponent instanceof CollectionTreeModel.Pair) {
                                CollectionTreeModel.Pair pair = (CollectionTreeModel.Pair) lastPathComponent;
                                Map map = new HashMap();
                                map.put(COLLECTION_ID_PARAM, pair.collection.getId());
                                map.put(SELECTED_OBJECTS_PARAM, Arrays.asList(new Object[]{pair.value}));
                                ContextBase ctx = new ContextBase(map);

                                try {
                                    cmd.execute(ctx);
                                } catch (Exception e1) {
                                    e1.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                                    // TODO add logging
                                }
                            }
                        }
                    }
                }
            }
        };
        treeTable.getTreeSelectionModel().addTreeSelectionListener(listener);
        ComponentListener componentListener = new ComponentAdapter() {
            @Override
            public void componentShown(ComponentEvent e) {
                listener.valueChanged(null);
            }
        };
        treeTable.addComponentListener(componentListener);

        return treeTable;
    }
}
